package com.hcbd.tdwt.ui.htct.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.ui.fuda.common.fragment.LocationFragment_;
import com.hcbd.tdwt.ui.htct.fragment.PositionFragment_;
import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.base.AuthManger;
import com.hcbd.tdwt.base.BaseActivity;
import com.hcbd.tdwt.base.BdManager;
import com.hcbd.tdwt.base.BottomBar;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.ImgSendManager;
import com.hcbd.tdwt.base.ReceiveImgManager;
import com.hcbd.tdwt.util.SharedPreferencesUtil;
import com.pangu.bdsdk2021.bluetooth.BluetoothManage;
import com.hcbd.tdwt.ui.htct.fragment.MessageFragment_;
import com.hcbd.tdwt.ui.htct.fragment.MyFragment_;
import com.hcbd.tdwt.ui.htct.fragment.SatelliteStatusFragment_;


import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

@SuppressLint("NonConstantResourceId")
@EActivity(R.layout.activity_main)
public class MainActivity extends BaseActivity {
    @ViewById
    RelativeLayout mainLL;
    @ViewById
    BottomBar bottomBar;
    private AuthManger authManger;
    private MessageFragment_ messageFragment;
    private MyFragment_ myFragment;
    private PositionFragment_ positionFragment;
    private SatelliteStatusFragment_ satelliteStatusFragment;
    private LocationFragment_ locationFragment;
    private SharedPreferencesUtil sp;
    @AfterViews
    protected void init() {
        sp=new SharedPreferencesUtil(this);
        messageFragment=new MessageFragment_();
        myFragment=new MyFragment_();
        positionFragment=new PositionFragment_();
        satelliteStatusFragment=new SatelliteStatusFragment_();
        locationFragment=new LocationFragment_();
        mainLL.setBackground(getDrawable(R.color.white));
        bottomBar.setBackground(getDrawable(R.color.white));
        authManger= AuthManger.getAuthManger();
        authManger.initDialog(this);
        BdManager.getInstance().initThreeOfficial(MainApp.getInstance());
        initEncoderCodeRate();
        manageExternalPermission();
        initBottomBar();

    }
    public void initEncoderCodeRate(){
        int currentIndex =sp.getAttributeInt(Constant.ENCODER_RATE);
        if(currentIndex==-1){
            sp.addAttribute(Constant.ENCODER_RATE,3);
            Constant.encoderCodeRate=3;
        }else{
            Constant.encoderCodeRate=currentIndex;
        }

    }
    public void initBottomBar() {
        bottomBar.setContainer(R.id.fl_container)
                .setFirstChecked(0)
                .setTitleBeforeAndAfterColor("#7A7D7F", "#0D346C")
                .addItem(satelliteStatusFragment,
                        "首页", R.drawable.home_satellite_pre_tt,
                        R.drawable.home_satellite_on_tt)
                .addItem(positionFragment,
                        "卫星", R.drawable.home_bd_pre_haige,
                        R.drawable.home_bd_on_haige)
                .addItem(messageFragment,
                        "消息", R.drawable.home_chat_pre_tt,
                        R.drawable.home_chat_on_tt)
                .addItem(locationFragment,
                        "地图", R.drawable.home_pos_pre_tt,
                        R.drawable.home_pos_on_tt)
                .addItem(myFragment,
                        "我的", R.drawable.home_my_pre_tt,
                        R.drawable.home_my_on_tt).buildTwo();
        bottomBar.setOnSwitchListener(currentFragment -> {
            if (currentFragment instanceof SatelliteStatusFragment_) {
                ((SatelliteStatusFragment_) bottomBar.getCurrentFragment()).onSwitch();
            }else if (currentFragment instanceof MessageFragment_) {
                ((MessageFragment_) bottomBar.getCurrentFragment()).onSwitch();
            }else if (currentFragment instanceof LocationFragment_) {
                ((LocationFragment_) bottomBar.getCurrentFragment()).onSwitch();
            }else if (currentFragment instanceof MyFragment_) {
                ((MyFragment_) bottomBar.getCurrentFragment()).onSwitch();
            } if (currentFragment instanceof PositionFragment_) {
                ((PositionFragment_) bottomBar.getCurrentFragment()).onSwitch();
            }
        });
    }
    private final int REQUEST_CODE=15;
    private void manageExternalPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 先判断有没有权限
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + this.getPackageName()));
                startActivityForResult(intent, REQUEST_CODE);
            }else{
                checkPermission();
            }
        }else{
            checkPermission();
        }
    }
    public void checkPermission(){
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, permissionRequestCode);
        }else{
            authManger.initZipSdk();
            initGps();
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUEST_CODE){
            checkPermission();
        }else if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Constant.TO_OPEN_GPS_REQUEST_CODE) {//开启GPS，重新添加地理监听
                initGps();
                hideWarnDialog();
            }else if(requestCode ==AuthManger.PIC_SC_CODE||requestCode ==AuthManger.VO_SC_CODE){
                authManger.setResult(requestCode,resultCode,data);
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            if (requestCode == Constant.TO_OPEN_GPS_REQUEST_CODE) {//取消开启GPS
                toast("不开启GPS导致某些功能无法使用！");
            }
        }

    }

    private void initGps() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            showWarnDialog("请打开手机GPS定位，\n否则APP将不能正常使用", view -> {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, Constant.TO_OPEN_GPS_REQUEST_CODE);
                hideWarnDialog();
            });
        } else {
            //初始化定位sdk
            MainApp.getInstance().initMap();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == permissionRequestCode) {
            authManger.initZipSdk();
            // MainApp.getInstance().initMap();
            initGps();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        BluetoothManage.getInstance().disConnect();
        ImgSendManager.getInstance().clear(Constant.SEND_MSG_FAIL);
        ReceiveImgManager.clear();
    }


}
